<template>
    <div class="content">
        <!-- openlayers地图 -->
        <div class="map">
            <OlMap ref="openlayersMap"></OlMap>
        </div>
        <OlPopup></OlPopup>
        <div style="position: absolute; left: var(--system-map-padding); top: var(--system-map-padding)">
            <el-button :type="baseType === 1 ? 'success' : 'primary'" @click="changeBaseMap('image', 1)">影像图</el-button>
            <el-button :type="baseType === 2 ? 'success' : 'primary'"
                @click="changeBaseMap('vector', 2)">矢量图</el-button>

        </div>
        <div style="position: absolute; left: var(--system-map-padding); bottom: var(--system-map-padding)">
            <div>
                <el-button @click="measure('area')">面积</el-button>
                <el-button @click="measure('distance')">距离</el-button>
                <el-button @click="clearMeasure">清除测量</el-button>
            </div>
            <div>
                <el-button @click="startDrawing('Point')">绘制点</el-button>
                <el-button @click="clearPoint('Point')">清除点</el-button>
                <el-button @click="startDrawing('LineString')">绘制线</el-button>
                <el-button @click="clearPoint('LineString')">清除线</el-button>
                <el-button @click="startDrawing('Polygon')">绘制面</el-button>
                <el-button @click="clearPoint('Polygon')">清除面</el-button>
                <el-button @click="cancelDrawing">取消绘制</el-button>
            </div>
            <div>
                <el-button @click="panTo">移动到点</el-button>
                <el-button @click="fitLayer">移动图层</el-button>
                <el-button @click="getLayerByName">名称获取图层</el-button>
                <el-button @click="setImageLayer">添加图片图层</el-button>
                <el-button @click="removeImageLayer">清除图片</el-button>
            </div>

        </div>
        <div style="position: absolute; right: var(--system-map-padding); top: var(--system-map-padding)">
            <el-button @click="addRealTimeData()">实况点</el-button>
            <el-button @click="addyjLayer()">预警</el-button>
            <!-- <DataTable :prj-name="'obj'" :spatial-query-model="true" :conditional-query-model="true"
                :edit-model="false"></DataTable> -->
        </div>
    </div>
</template>

<script setup>
import OlMap from '@/components/ol-map/index.vue';
import OlPopup from '@/components/ol-popup/index.vue';
import DataTable from './data-table/index.vue';

import { useMapStoreHook } from '@/store/map';
import sksj from './data.json'

// 初始化map
const mapStore = useMapStoreHook();
const { olMap, extent } = storeToRefs(mapStore);

let form = reactive({
    text: ''
});

let rules = reactive({
    text: [
        {
            required: true,
            message: '请输入文字',
            trigger: 'change'
        }
    ]
});


const formRef = ref();
//提交表单，查询
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            console.log(form);
            ElMessage.success('提交成功');
        } else {
            ElMessage.warning('请按规则填写');
            return false;
        }
    });
};
// 重置表单
const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
    ElMessage.success('重置成功');
};
let pointLayer = null;
//加点
const addPoint = (data) => {
    console.log("data:", data);
    if (!pointLayer) {
        pointLayer = olMap.value.layer.createVectorLayer('点图层', 35);
    }
    // pointLayer.value.getSource().clear();
    olMap.value.vector.addPoint({
        coordinates: data,
        layer: pointLayer,
        style: {
            radius: 10,
            fillColor: '#ff473d',
            strokeWidth: 1,
            strokeColor: 'rgba(255, 255, 255, 0.5)'
        },
        info: {
            name: 'pointInfo',
            info: { name: '测试' }
        }
    });
};
let lineLayer = null;
const addLine = (data) => {
    if (!lineLayer) {
        lineLayer = olMap.value.layer.createVectorLayer('线图层', 25);
    }
    lineLayer.getSource().clear();
    olMap.value.vector.addLine({
        coordinates: data,
        layer: lineLayer,
        style: {},
        info: {
            name: 'pointInfo',
            info: { name: '测试' }
        }
    });
};
let polygonLayer = null;
//加面
const addPolygon = (data) => {
    if (!polygonLayer) {
        polygonLayer = olMap.value.layer.createVectorLayer('面图层', 15);
    }
    polygonLayer.getSource().clear();
    olMap.value.vector.addPolygon({
        coordinates: data,
        layer: polygonLayer,
        style: {},
        info: {
            name: 'pointInfo',
            info: { name: '测试' }
        }
    });
};
//清除点
const clearPoint = (type) => {
    switch (type) {
        case 'Point':
            if (pointLayer) {
                pointLayer.getSource().clear();
            }
            break;
        case 'LineString':
            if (lineLayer) {
                lineLayer.getSource().clear();
            }
            break;
        case 'Polygon':
            if (polygonLayer) {
                polygonLayer.getSource().clear();
            }
            break;
    }

};

onMounted(() => {
    // addRealTimeData、()
    // addyjLayer()
});

const baseType = ref(1)
/**
 * 1，切换地图底图类型
 * @param type 地图类型 image:影像图 vector:矢量图 
 */
const changeBaseMap = (type, i) => {
    baseType.value = i;
    olMap.value.layer.changeBaseMap(type);
};
//测量
const measure = (type) => {
    olMap.value.measure.measure(type);
};
//清除测量
const clearMeasure = () => {
    olMap.value.measure.clear();
}
//绘制
const startDrawing = (type) => {
    olMap.value.draw.startDrawing(type, false, (coordinates) => {
        console.log('绘制的坐标：', coordinates);
        switch (type) {
            case 'Point':
                //绘制点
                addPoint(coordinates[0])
                break;
            // 绘制线
            case 'LineString':
                addLine(coordinates[0])
                break;
            // 绘制面
            case 'Polygon':
                addPolygon(coordinates[0])
                break;
        }

    });
};
//取消绘制
const cancelDrawing = () => {
    olMap.value.draw.cancelDrawing();
};
//移动地图到某个点
const panTo = () => {
    olMap.value.panTo({
        coordinates: [116, 35], //中心坐标
        duration: 1000, //移动时间
        zoom: 10 //缩放级别
    });
}
//移动地图到某个图层
const fitLayer = () => {
    if (olMap.value.layer.getLayerByName('点图层')) {
        olMap.value.layer.fitLayer({
            layer: olMap.value.layer.getLayerByName('点图层'), //图层
            duration: 1000, //移动时间
            paddingList: [100, 100, 100, 100] //添加内边距
        });
    }
};
//通过图层的layerName属性获取图层
const getLayerByName = () => {
    const name = olMap.value.layer.getLayerByName('点图层')
    console.log("name:", name);
    return name
};
//添加图片图层
const setImageLayer = () => {
    olMap.value.layer.setImageLayer(
        'https://s11.ax1x.com/2023/08/14/pPMmfIS.jpg', //图片地址
        [113, 32, 124, 39], //范围
        0.8 //透明度
    );
};

//添加图片图层
const removeImageLayer = () => {
    olMap.value.layer.removeImageLayer();
};
//3 添加实况数据
const addRealTimeData = () => {
    const SkPointLayer = olMap.value.layer.createVectorLayer('实况图层', 35);
    SkPointLayer.getSource().clear();
    sksj?.RECORDS?.forEach(el => {
        const objList = [
            { l: 0, r: 0.1, v: '#FFFFFF' },
            { l: 0.1, r: 1.6, v: '#6DB78D' },
            { l: 1.6, r: 7, v: '#36AA35' },
            { l: 7, r: 15, v: '#B8954B' },
            { l: 15, r: 40, v: '#FF0000' },
            { l: 40, r: 50, v: '#B200BC' },
            { l: 50, r: undefined, v: '#31FFFF' }
        ]
        //在l 和r 范围之间返回v
        // const color = objList.find(item => el.rain >= item.l && el.rain <= item.r)?.v
        const color = objList.find(item => el.rain >= item.l && (el.rain <= item.r || !item.r))?.v
        //添加点和文本(单个)
        olMap.value.vector.addPointWithText({
            coordinates: [+el.lon, +el.lat],
            layer: SkPointLayer,
            pointStyle: {
                radius: 5,
                fillColor: color,
                strokeWidth: 1,
                strokeColor: 'rgba(255, 255, 255, 0.5)'
            },
            textStyle: {
                text: el.stationname,
                offsetY: 20
            },
            info: {
                name: 'SksjPointInfo',
                info: {
                    stationid: el.stationid,
                    stationname: el.stationname,
                    rain: el.rain
                }
            }
        })
    })
    showLayer('实况图层')
}
//添加预警图层
const addyjLayer = () => {
    const yjLayer = olMap.value.layer.createVectorLayer('预警图层', 35);
    yjLayer.getSource().clear();
    const arr = [
        {
            points: [
                [112.48554, 28.22753],
                [112.56831, 28.22301],
                [112.58186, 28.16733],
                [112.56831, 28.11615],
                [112.47500, 28.10562],
                [112.44339, 28.11766],
                [112.42383, 28.13271],
                [112.42082, 28.15378],
                [112.41781, 28.17184],
                [112.41781, 28.20194],
                [112.43286, 28.22753],
                [112.45243, 28.22903],
                [112.48554, 28.22753]
            ],
            color: '65535'
        },
        {
            points: [
                [112.76698, 28.35696],
                [112.82267, 28.38857],
                [112.87685, 28.35847],
                [112.85729, 28.29526],
                [112.81213, 28.28322],
                [112.76698, 28.29375],
                [112.74591, 28.33439],
                [112.74441, 28.34643],
                [112.76698, 28.35696]
            ],
            //橙色
            color: '16753665'
        },
        {
            points: [
                [113.13422, 28.29225],
                [113.21248, 28.29526],
                [113.24258, 28.20947],
                [113.18389, 28.12218],
                [113.10562, 28.11615],
                [113.05144, 28.20495],
                [113.05596, 28.25763],
                [113.09659, 28.28623],
                [113.13422, 28.29225]
            ],
            color: '255'
        },
    ]
    olMap.value.layer.addGridArea(arr)
    showLayer('预警图层')
}
// 显示对应的图层
const showLayer = (type) => {
    //隐藏所有图层
    let layers = olMap.value.map.getLayers().getArray();
    layers.forEach((layer) => {
        // 隐藏图层
        const l = ['预警图层', '实况图层'].includes(layer.get("layerName"))
        l && layer.setVisible(false)
    })
    olMap.value.layer.getLayerByName(type)?.setVisible(true)
}

</script>
<style lang="less" scoped>
.content {
    display: flex;
    justify-content: center;
    align-items: center;
    height: auto;
    position: relative;

    .map {
        width: 100vw;
        height: 100%;
    }
}
</style>
